<template>
  <a-modal
    :title="title"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item label="父级">
          <a-tree-select
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="treeData"
            placeholder="Please select"
            tree-default-expand-all
            v-decorator="['tree']">
          </a-tree-select>
        </a-form-item>
        <a-form-item label="方法">
          <a-input v-decorator="['name', {rules: [{required: true, min: 1, message: '请至少输入两个字符'}]}]" />
        </a-form-item>
        <a-form-item label="方法名称">
          <a-input v-decorator="['title']" />
        </a-form-item>
        <a-form-item>
          <a-input type="hidden" v-decorator="['key']">
          </a-input>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { getTree } from '@/api/action'
// 表单字段
const fields = ['name', 'title', 'key', 'tree']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    title: {
      type: String,
      default: () => ''
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      edit: true,
      form: this.$form.createForm(this),
      treeData: []
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  watch: {
    title: function (val) {
      if (val === '编辑方法') {
        this.edit = false
      } else {
        this.edit = true
      }
    }
  },
  methods: {
    getTree () {
          getTree().then((res) => {
            console.log(res)
          if (res.code === 0) {
              this.treeData = res.data
          } else {
              this.$message.error(res.message)
          }
        }).catch((err) => {
          console.log(err)
        })
      }
  },
  mounted () {
    this.getTree()
  }
}
</script>
